'use strict';
module.exports = {
	/**
	 * 该函数的功能是执行用户付费数据回传。
	 * 当用户支付完成后，微信支付会发送支付回调给vk-pay云函数，vk-pay处理完充值金豆或充值会员的逻辑后，调用本函数进行数据回传
	 * 
	 * client/user/pub/callback 前端调用的url参数地址
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			out_trade_no,
			total_fee,
			_add_time,
			_add_time_str
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		_add_time_str = vk.pubfn.timeFormat(_add_time_str, "yyyy-MM-dd hh:mm:ss");
		let douyin_percent = 100; //抖音回传比例，默认全部回传
		let url = "https://clue.oceanengine.com/outer/wechat/applet/token/1757233229756557"; //巨量资产化小程序回传url
		let token = "82A9DF19BD811D85ECA0DB54D13DC4A6"; //巨量资产化小程序回传token
		let kuaishou_percent = 100; //快手回传比例，默认全部回传
		let baidu_percent = 100; //百度回传比例，默认全部回传
		let tengxun_percent = 100; //腾讯回传比例，默认全部回传
		let uc_percent = 100; //UC回传比例，默认全部回传
		let oppo_percent = 100; //OPPO回传比例，默认全部回传
		let owner_id = "1000218511";
		let api_id = "api";
		let api_key = "api";
		let douyinMinPrice = 0; //最低回传金额
		let kuaishouMinPrice = 0;
		let baiduMinPrice = 0;
		let ucMinPrice = 0;
		let tengxunMinPrice = 0;
		let oppoMinPrice = 0;

		let newuser = true; //是否仅回传当日新用户的订单,默认开启
		let firstorder = true; //是否仅回传用户的第一笔订单,默认开启
		let baidu_token = "";

		//使用vk公共函数需现在页面顶部引入VK框架，获取今日0点时间戳
		let {
			todayStart
		} = vk.pubfn.getCommonTime(new Date());

		//======获取充值订单信息开始======
		let temp_info = await db.collection('a_recharge').where({
			out_trade_no: out_trade_no
		}).get()
		var orderinfo = temp_info.data[0];
		let clickid = temp_info.data[0].clickid || "";

		if (!clickid || clickid == "NoClickid" || clickid.length < 17) {
			res.tips = "不存在clickid";
			return res;
		}
		//======获取充值订单信息结束======

		//======获取回传比例开始======
		let percent = null
		let tfurlpercent = await db.collection('a_config').where({
			name: "RebackPercent",
			tfid: orderinfo.tfid //添加这条数据的代理商ID
		}).get()

		if (tfurlpercent.data.length != 0) {
			percent = tfurlpercent
		} else {
			percent = await db.collection('a_config').where({
				name: "RebackPercent",
				user_id: orderinfo.invite_code || 0 //添加这条数据的代理商ID
			}).get()
		}

		if (percent.data[0]) {
			console.log("存在代理商比例数据", percent);
			url = percent.data[0].douyin_url; //抖音广告资产化回传URL
			token = percent.data[0].douyin_token; //抖音广告资产化回传token
			douyin_percent = percent.data[0].douyin || 100; //抖音回传比例
			kuaishou_percent = percent.data[0].kuaishou || 100; //快手回传比例
			baidu_percent = percent.data[0].baidu || 100; //百度回传比例
			tengxun_percent = percent.data[0].tengxun || 100; //腾讯回传比例
			uc_percent = percent.data[0].uc || 100; //UC回传比例
			oppo_percent = percent.data[0].oppo || 100; //oppo回传比例
			owner_id = percent.data[0].oppo_owner_id;
			api_id = percent.data[0].oppo_api_id;
			api_key = percent.data[0].oppo_api_key;
			newuser = percent.data[0].newuser; //是否仅回传当日新用户的订单
			firstorder = percent.data[0].firstorder; //是否仅回传用户的第一笔订单
			baidu_token = percent.data[0].baidu_token; //百度回传token
			douyinMinPrice = percent.data[0].douyinMinPrice || 0; //最低回传金额
			kuaishouMinPrice = percent.data[0].kuaishouMinPrice || 0;
			baiduMinPrice = percent.data[0].baiduMinPrice || 0;
			ucMinPrice = percent.data[0].ucMinPrice || 0;
			tengxunMinPrice = percent.data[0].tengxunMinPrice || 0;
			oppoMinPrice = percent.data[0].oppoMinPrice || 0;
		} else {
			console.log("不存在代理商比例数据");
		}

		let randomnum = Math.floor(Math.random() * (99 - 0)) + 0; //生成一个0到99的随机数
		//======获取回传比例结束======


		//查询已支付订单数量，如已有一条以上的支付订单，则不回传数据给巨量
		let user_recharge_num = await db.collection('a_recharge').where({
			pay_status: 1,
			user_id: orderinfo.user_id
		}).count()

		// //如果未开启【仅回传当日新用户的订单】，就把todayStart置为0，这样user_register_date>todayStart永远成立
		// if (newuser) {
		// 	console.log("仅回传今日新用户的充值订单,此处不return,继续执行下面逻辑");
		// } else {
		// 	todayStart = 0
		// 	console.log("已把todayStart改为0");
		// }

		// //如果开启了仅回传用户首笔订单，当查出的已支付订单大于1时，就可以直接return。
		// if (firstorder) {
		// 	console.log("仅回传用户首笔订单");
		// 	if (user_recharge_num.total > 1) {
		// 		console.log("已付费订单数量大于1，直接结束");
		// 		return res;
		// 	}
		// }

		//存在clickid，且该用户的注册时间是今天，则向巨量发送新用户首次付费回传
		if (orderinfo.user_register_date > todayStart) {
			console.log("用户注册时间为今天或不存在用户注册时间限制");
			//========抖音回传开始========
			if (orderinfo.tg_pt == "douyin") {
				if (total_fee < douyinMinPrice * 100) {
					let addvktest = await db.collection('vk-test').add({
						tips: "低价格订单不回传抖音",
						out_trade_no: out_trade_no,
						total_fee: total_fee,
						_add_time: _add_time,
						_add_time_str: _add_time_str
					})
					return res;
				}
				//先获取用户表信息，如果用户信息里存在clud_token,则执行2.0回传接口
				let orderUser = await db.collection('uni-id-users').where({
					_id: orderinfo.user_id
				}).get();

				if (orderUser.data[0].clue_token) {
					let nonce = 8889;
					let times = vk.pubfn.toDecimal(new Date() / 1000, 0);

					const crypto = require('crypto');
					const sha1 = crypto.createHash('sha1');

					let strList = [token, times, nonce];
					strList.sort();
					let buffer = "";
					strList.forEach(str => {
						buffer += str;
					})
					let sign = sha1.update(buffer).digest('hex');
					console.log("sign=", sign);

					let reback_url = url + "?timestamp=" + times + "&nonce=" + nonce + "&signature=" + sign;

					res.jlresult = await uniCloud.httpclient.request(reback_url, {
						method: 'POST',
						data: {
							"clue_token": orderUser.data[0].clue_token,
							"open_id": orderUser.data[0].wx_openid['mp-weixin'],
							"event_type": "2", //参考：https://bytedance.feishu.cn/docx/doxcnmjDmhXc1Vial05xpvdu9ed
							"props": {
								"pay_amount": total_fee || 1 //单位：分
							}
						},
						contentType: 'json',
						dataType: 'json'
					})
					console.log("res.jlresult=", res.jlresult);
				} else {
					// 回传支付事件给巨量
					res.jlurl = "https://analytics.oceanengine.com/api/v2/conversion"
					res.jlresult = await uniCloud.httpclient.request(res.jlurl, {
						method: 'POST',
						data: {
							"event_type": "active_pay",
							"context": {
								"ad": {
									"callback": clickid, //callback 这里需要填写的就是从启动参数里获取的 clickid
								}
							},
							"properties": {
								"pay_amount": total_fee, //回传付费金额
							},
							//附加属性回传http://event-manager.oceanengine.com/docs/8650/all_properties/
							"timestamp": _add_time
						},
						contentType: 'json',
						dataType: 'json'
					})
				}
				if (res.jlresult.data.code == 0 || res.jlresult.data.status == 200) {
					// 返回被修改的记录条数
					let num = await vk.baseDao.update({
						dbName: "a_recharge", // 表名
						whereJson: { // 条件
							out_trade_no: out_trade_no
						},
						dataJson: { // 需要修改的数据
							is_backhaul: true //订单是否回传
						}
					});
				}


				// 回传记录入库
				let addhc1 = await db.collection('jl_huichuanjilu').add({
					type: "active_pay",
					platform: "douyin",
					user_id: orderinfo.user_id,
					tfid: orderinfo.tfid || "",
					agent_id: orderinfo.invite_code || 0,
					middleman_id: orderinfo.middleman_id || 0,
					adid: orderinfo.ad_id,
					clickid: clickid,
					money: total_fee,
					result: res.jlresult.data,
					out_trade_no: out_trade_no,
					time: _add_time,
					time_str: _add_time_str
				})
			}
			//========抖音回传结束========

			//========快手回传开始========
			if (orderinfo.tg_pt == "kuaishou") {
				if (total_fee < kuaishouMinPrice * 100) {
					let addvktest = await db.collection('vk-test').add({
						tips: "低价格订单不回传快手",
						out_trade_no: out_trade_no,
						total_fee: total_fee,
						_add_time: _add_time,
						_add_time_str: _add_time_str
					})
					return res;
				}
				// 回传支付事件给快手广告平台
				let nows = new Date().getTime()
				let purchase_amount = orderinfo.shifu_amount / 100;
				purchase_amount = purchase_amount.toFixed(2)
				let ksurl =
					"http://ad.partner.gifshow.com/track/activate?event_type=3&purchase_amount=" +
					purchase_amount + "&event_time=" + nows + "&callback=" + clickid
				let kshuichuan_result = await uniCloud.httpclient.request(ksurl, {
					method: 'GET',
					data: {},
					contentType: 'json', // 指定以application/json发送data内的数据
					dataType: 'json' // 指定返回值为json格式，自动进行parse
				})
				//回传返回结果为什么要加一个code？因为巨量广告的回传返回值有code,为方便后续通过code来统计回传成功次数，故在快手处也加一个code参数
				//快手返回成功形式为"result":1,"host-name":"ad-rs-bjmt-ad467.idcyz.hb1.kwaidc.com"
				if (kshuichuan_result.data.result == 1) {
					kshuichuan_result.data.code = 0
				}
				if (kshuichuan_result.data.result == 1) {
					// 返回被修改的记录条数
					let num = await vk.baseDao.update({
						dbName: "a_recharge", // 表名
						whereJson: { // 条件
							out_trade_no: out_trade_no
						},
						dataJson: { // 需要修改的数据
							is_backhaul: true //订单是否回传
						}
					});
				}
				// 回传记录入库
				let addhc2 = await db.collection('jl_huichuanjilu').add({
					type: "active_pay",
					platform: "kuaishou",
					user_id: orderinfo.user_id,
					tfid: orderinfo.tfid || "",
					agent_id: orderinfo.invite_code || 0,
					middleman_id: orderinfo.middleman_id || 0,
					adid: orderinfo.ad_id,
					clickid: clickid,
					money: total_fee,
					result: kshuichuan_result.data,
					out_trade_no: out_trade_no,
					time: _add_time,
					time_str: _add_time_str
				})
			}
			//========快手回传结束========

			//========UC回传开始========
			if (orderinfo.tg_pt == "uc") {
				if (total_fee < ucMinPrice * 100) {
					let addvktest = await db.collection('vk-test').add({
						tips: "低价格订单不回传UC",
						out_trade_no: out_trade_no,
						total_fee: total_fee,
						_add_time: _add_time,
						_add_time_str: _add_time_str
					})
					return res;
				}
				console.log("执行UC回传");
				// 回传支付事件给UC广告平台
				let nows = new Date().getTime()
				let purchase_amount = orderinfo.shifu_amount / 100;
				purchase_amount = purchase_amount.toFixed(2) //金额单位转为元，且保留2位小数
				let ucurl = clickid + "&type=66&money=" + purchase_amount + "&event_time=" + nows
				let uchuichuan_result = await uniCloud.httpclient.request(ucurl, {
					method: 'GET',
					data: {},
					contentType: 'json',
					dataType: 'json'
				})

				if (uchuichuan_result.data.result == 1) {
					uchuichuan_result.data.code = 0
				}
				if (uchuichuan_result.data.result == 1) {
					// 返回被修改的记录条数
					let num = await vk.baseDao.update({
						dbName: "a_recharge", // 表名
						whereJson: { // 条件
							out_trade_no: out_trade_no
						},
						dataJson: { // 需要修改的数据
							is_backhaul: true //订单是否回传
						}
					});
				}
				// 回传记录入库
				let uc_hc_log = await db.collection('jl_huichuanjilu').add({
					type: "active_pay",
					platform: "uc",
					user_id: orderinfo.user_id,
					tfid: orderinfo.tfid || "",
					agent_id: orderinfo.invite_code || 0,
					middleman_id: orderinfo.middleman_id || 0,
					adid: orderinfo.ad_id,
					clickid: clickid,
					money: total_fee,
					result: uchuichuan_result.data,
					out_trade_no: out_trade_no,
					time: data._add_time,
					time_str: data._add_time_str
				})
			}
			//========UC回传结束========

			//========腾讯回传开始========
			if (orderinfo.tg_pt == "tengxun") {
				let request_id = vk.pubfn.getUniCloudRequestId();
				let look_log = await db.collection('vk-test').add({
					tips: "查看腾讯回传",
					request_id: request_id,
					time: data._add_time,
					time_str: data._add_time_str
				})
				console.log("执行腾讯广告回传");
				//获取用户的callback 
				let chudian = await vk.baseDao.findByWhereJson({
					dbName: "jl_chudian",
					whereJson: {
						callback: clickid,
					}
				});
				console.log("351行=》", chudian);
				let callback_url = chudian.callback_url
				//获取用户的openid 
				let wechat_openid = chudian.wechat_openid
				//获取短剧名称
				let product_name = orderinfo.tv_name || ''
				//获取短剧的id 
				let tv = await vk.baseDao.findByWhereJson({
					dbName: "a_tv",
					whereJson: {
						tv_name: product_name,
					}
				});
				console.log("364行=》", tv);
				let product_id = tv._id
				// 回传支付事件给腾讯广告平台
				let nows = new Date().getTime()
				let ts_10 = Math.round(new Date().getTime() / 1000).toString();
				// 回传支付事件给腾讯https://docs.qq.com/pdf/DQm1PUWRHZVdudkRG?
				//回传事件类型：https://developers.e.qq.com/docs/guide/conversion/new_version/Web_api
				// let tengxunurl =
				// 	"http://tracking.e.qq.com/conv/web?clickid=" + clickid + "&action_time=" + ts_10 +
				// 	"&action_type=PURCHASE&value=" + total_fee + "&link=tracking.e.qq.com";
				let tengxunurl = callback_url
				let tengxunhuichuan_result = await uniCloud.httpclient.request(tengxunurl, {
					"headers": {
						"Content-Type": 'application/json',
						"cache-control": 'no-cache'
					},
					method: 'POST',
					data: {
						"actions": [{
							"outer_action_id": "", // （选填）客户唯一行为id
							"action_time": ts_10,
							"user_id": { // user_id， 对应小程序的openid
								"wechat_openid": wechat_openid, // 必填
								"wechat_app_id": "wxdad3b6f00b92a6c2", // 微信类上报必填，且必须通过授权。授权请参考微信数据接入
							},
							"trace": {
								"click_id": clickid // 必填 click_id
							},
							"action_type": "PURCHASE", // 必填 行为类型，下单为COMPLETE_ORDER、付费为PURCHASE
							"action_param": {
								"product_id ": product_id, //必填，书籍D， 
								"value": total_fee, //必填，付费金额（分）
								"product_name": product_name, //小说（或短剧剧名）书名，格式小说名-书城名称或者剧名-剧城名称
								"Object": "1" // 回传类型
							}
						}]
					},
					// contentType: 'json',
					// dataType: 'json'
				})

				if (tengxunhuichuan_result.status == 200) {
					// 返回被修改的记录条数
					let num = await vk.baseDao.update({
						dbName: "a_recharge", // 表名
						whereJson: { // 条件
							out_trade_no: out_trade_no
						},
						dataJson: { // 需要修改的数据
							is_backhaul: true //订单是否回传
						}
					});
				}

				// 回传记录入库
				let uc_hc_log = await db.collection('jl_huichuanjilu').add({
					type: "active_pay",
					platform: "tengxun",
					user_id: orderinfo.user_id,
					tfid: orderinfo.tfid || "",
					agent_id: orderinfo.invite_code || 0,
					middleman_id: orderinfo.middleman_id || 0,
					adid: orderinfo.ad_id,
					clickid: clickid,
					money: total_fee,
					result: tengxunhuichuan_result.data,
					out_trade_no: out_trade_no,
					time: data._add_time,
					time_str: data._add_time_str
				})
			}
			//========腾讯回传结束========

			//========百度回传开始========
			if (orderinfo.tg_pt == "baidu") {
				console.log("执行百度回传");
				if (total_fee < baiduMinPrice * 100) {
					let addvktest = await db.collection('vk-test').add({
						tips: "低价格订单不回传百度",
						out_trade_no: out_trade_no,
						total_fee: total_fee,
						_add_time: _add_time,
						_add_time_str: _add_time_str
					})
					return res;
				}

				let nows = new Date().getTime()
				console.log("baidu_token=", baidu_token);
				console.log("clickid=", clickid);
				// 回传支付事件给百度
				let baiduurl = "https://ocpc.baidu.com/ocpcapi/api/uploadConvertData"
				let baiduhuichuan_result = await uniCloud.httpclient.request(baiduurl, {
					method: 'POST',
					data: {
						"token": baidu_token, //无忧短剧token
						"conversionTypes": [{
							"logidUrl": "bd_vid=" + clickid,
							"newType": 118, //118=付费观剧，参考：https://dev2.baidu.com/content?sceneType=0&pageId=101207&nodeId=655
							"convertValue": total_fee, //转化金额，单位分，https://dev2.baidu.com/content?sceneType=0&pageId=101211&nodeId=658&subhead=
							"attributeSource": 0, //（转化来源：百度（0），自然流量（1），竞媒（2））
							"interactionsType": 1 //（归因请求方式，点击(1), 播放(2), 关注(3), 分享(4), 点赞(5), 曝光（6）不传使用1，默认为点击归因
						}]
					},
					contentType: 'json', // 指定以application/json发送data内的数据
					dataType: 'json' // 指定返回值为json格式，自动进行parse
				})

				if (baiduhuichuan_result.data.result == 1) {
					baiduhuichuan_result.data.code = 0
				}
				if (baiduhuichuan_result.data.header.status == 0) {
					// 返回被修改的记录条数
					let num = await vk.baseDao.update({
						dbName: "a_recharge", // 表名
						whereJson: { // 条件
							out_trade_no: out_trade_no
						},
						dataJson: { // 需要修改的数据
							is_backhaul: true //订单是否回传
						}
					});
				}
				// 回传记录入库
				let uc_hc_log = await db.collection('jl_huichuanjilu').add({
					type: "active_pay",
					platform: "baidu",
					user_id: orderinfo.user_id,
					tfid: orderinfo.tfid || "",
					agent_id: orderinfo.invite_code || 0,
					middleman_id: orderinfo.middleman_id || 0,
					adid: orderinfo.ad_id,
					clickid: clickid,
					money: total_fee,
					result: baiduhuichuan_result.data,
					out_trade_no: out_trade_no,
					time: data._add_time,
					time_str: data._add_time_str
				})
			}
			//========百度回传结束========

			//========OPPO回传开始========
			if (orderinfo.tg_pt == "oppo") {
				console.log("执行OPPO回传");
				if (total_fee < oppoMinPrice * 100) {
					let addvktest = await db.collection('vk-test').add({
						tips: "低价格订单不回传OPPO",
						out_trade_no: out_trade_no,
						total_fee: total_fee,
						_add_time: _add_time,
						_add_time_str: _add_time_str
					})
					return res;
				}

				const crypto = require('crypto');
				const sha1 = crypto.createHash('sha1');

				let times = vk.pubfn.toDecimal(new Date() / 1000, 0);
				let beforesha1 = api_id + api_key + times;
				let sign = sha1.update(beforesha1).digest('hex');
				console.log("sign=", sign);

				//1.加密 
				let input = owner_id + "," + api_id + "," + times + "," + sign;
				var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
				var output = "";
				var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
				var i = 0;
				while (i < input.length) {
					chr1 = input.charCodeAt(i++);
					chr2 = input.charCodeAt(i++);
					chr3 = input.charCodeAt(i++);
					enc1 = chr1 >> 2;
					enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
					enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
					enc4 = chr3 & 63;
					if (isNaN(chr2)) {
						enc3 = enc4 = 64;
					} else if (isNaN(chr3)) {
						enc4 = 64;
					}
					output = output +
						_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
						_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
				}
				console.log("output=", output);

				console.log("clickid=", clickid);
				// 回传支付事件给OPPO
				let oppourl = "https://sapi.ads.oppomobile.com/v1/clue/sendData"
				let oppohuichuan_result = await uniCloud.httpclient.request(oppourl, {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json',
						Authorization: "Bearer " + output
					},
					data: {
						"ip": orderinfo.ip || "127.0.0.1",
						"transformType": 101,
						"ownerId": owner_id,
						"pageId": orderinfo.pageId || "1",
						"tid": clickid,
						"items": [{
								"column": "姓名",
								"desc": "姓名输入框",
								"ifNeed": true,
								"type": "1",
								"value": "小红"
							},
							{
								"column": "电话",
								"desc": "电话",
								"ifNeed": true,
								"type": "3",
								"value": "18783687596"
							}
						],
						"lbid": "1_0_0"
					},
					contentType: 'json', // 指定以application/json发送data内的数据
					dataType: 'json' // 指定返回值为json格式，自动进行parse
				})

				if (oppohuichuan_result.data.result == 1) {
					oppohuichuan_result.data.code = 0
				}
				if (oppohuichuan_result.data.code == 0) {
					// 返回被修改的记录条数
					let num = await vk.baseDao.update({
						dbName: "a_recharge", // 表名
						whereJson: { // 条件
							out_trade_no: out_trade_no
						},
						dataJson: { // 需要修改的数据
							is_backhaul: true //订单是否回传
						}
					});
				}
				// 回传记录入库
				let uc_hc_log = await db.collection('jl_huichuanjilu').add({
					type: "active_pay",
					platform: "oppo",
					user_id: orderinfo.user_id,
					tfid: orderinfo.tfid || "",
					agent_id: orderinfo.invite_code || 0,
					middleman_id: orderinfo.middleman_id || 0,
					adid: orderinfo.ad_id,
					clickid: clickid,
					money: total_fee,
					result: oppohuichuan_result.data,
					out_trade_no: out_trade_no,
					time: data._add_time,
					time_str: data._add_time_str
				})
			}
			//========OPPO回传结束========
		} else {
			res.tips = "未执行回传";
			console.log("未执行回传");
		}

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}